package org.system.core.security.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.system.core.domain.model.LoginUser;
import org.system.core.service.system.TokenService;
import org.system.core.utils.SecurityUtils;
import org.system.core.utils.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author baoRoot
 * token过滤器 验证token有效性 （OncePerRequestFilter：确保每个 HTTP 请求只执行一次过滤操作）
 */
@Component
public class JwtAuthenticationTokenFilters extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain chain
    ) throws ServletException, IOException {
        //获取登录用户
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            //验证用户和认证信息
            tokenService.verifyToken(loginUser);
            //创建一个身份验证令牌对象
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //设置认证到 SecurityContext，这意味着当前用户的身份信息已经成功地被 Spring Security 认证系统捕获，后续可以在整个应用中使用
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        //进行下一步过滤
        chain.doFilter(request, response);
    }
}
